﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

using Android.App;
using Android.Content;
using Android.Database;
using Android.OS;
using Android.Provider;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace Medicine.Helpers
{
    public class OtherHelpers
    {
        /// <summary>
        /// 数据克隆
        /// </summary>
        public static class Clone
        {
            /// <summary>
            /// 深克隆
            /// </summary>
            /// <param name="inObj">传入需要克隆的类（引用类型）</param>
            /// <returns></returns>
            public static object DeepClone(object inObj)
            {

                BinaryFormatter bf = new BinaryFormatter();

                MemoryStream ms = new MemoryStream();

                bf.Serialize(ms, inObj);

                ms.Seek(0, SeekOrigin.Begin);

                return bf.Deserialize(ms);
            }

        }

        /// <summary>
        /// 选中文件转换成实际路径
        /// </summary>
        public static class RealyPath
        {
            #region 获取选中文件实际路径
            /// <summary>
            /// 获取实际路径
            /// </summary>
            /// <param name="activity"><see cref="Activity"/></param>
            /// <param name="uri">地址信息</param>
            /// <returns></returns>
            public static string GetRealyPath(Activity activity, Android.Net.Uri uri)
            {
                bool isKitkat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;
                if (isKitkat && DocumentsContract.IsDocumentUri(activity, uri))
                {
                    string docId = DocumentsContract.GetDocumentId(uri);

                    if (IsExternalStorageDocument(uri))
                    {
                        var docIdArray = docId.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                        string docType = docIdArray[0];
                        if (docType.Contains("primary"))
                            return Android.OS.Environment.ExternalStorageDirectory + "/" + docIdArray[1];
                    }
                    else if (IsDownloadsDocument(uri))
                    {
                        Android.Net.Uri contentUri = ContentUris.WithAppendedId(Android.Net.Uri.Parse("content://downloads/public_downloads"),
                                                                                    Convert.ToInt64(docId));
                        return GetDataColumn(activity, uri);
                    }
                    else if (IsMediaDocument(uri))
                    {
                        var docIdArray = docId.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                        string docType = docIdArray[0];
                        Android.Net.Uri contentUri = null;
                        if (docType.Contains("image"))
                            contentUri = MediaStore.Images.Media.ExternalContentUri;
                        else if (docType.Contains("video"))
                            contentUri = MediaStore.Video.Media.ExternalContentUri;
                        else if (docType.Contains("audio"))
                            contentUri = MediaStore.Audio.Media.ExternalContentUri;

                        string selection = "_id=?";
                        String[] selectionArgs = new String[] { docIdArray[1] };
                        return GetDataColumn(activity, contentUri, selection, selectionArgs);
                    }
                }
                else if (uri.Scheme.Contains("content"))
                    return GetDataColumn(activity, uri);

                return string.Empty;
            }

            private static string GetDataColumn(Activity activity,
                                                Android.Net.Uri uri,
                                                String selection = null,
                                                String[] selectionArgs = null)
            {
                ICursor cursor = null;
                string column = "_data";
                string[] projection = { column };
                try
                {
                    cursor = activity.ContentResolver.Query(uri, projection, selection, selectionArgs, null);
                    if (cursor != null && cursor.MoveToFirst())
                    {
                        int columnIndex = cursor.GetColumnIndexOrThrow(column);
                        return cursor.GetString(columnIndex);
                    }
                }
                catch
                {
                    if (cursor != null)
                        cursor.Dispose();
                }

                return string.Empty;
            }

            private static bool IsExternalStorageDocument(Android.Net.Uri uri)
                => uri.Authority.Contains("com.android.externalstorage.documents");
            private static bool IsDownloadsDocument(Android.Net.Uri uri)
                => uri.Authority.Contains("com.android.providers.downloads.documents");
            private static bool IsMediaDocument(Android.Net.Uri uri)
                => uri.Authority.Contains("com.android.providers.media.documents");
            #endregion
        }
    }
}